package com.hngy.xpq.broadcastdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private  MyReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.动态注册广播，注意要在onDestroy()函数中注销广播unregisterReceiver(receiver);
        receiver = new MyReceiver(); //实例化广播接收者
        String action = "mahuateng";
        IntentFilter intentFilter = new IntentFilter(action);
        registerReceiver(receiver,intentFilter); //注册广播
        Button button= (Button) findViewById(R.id.Broadcast);//获取布局文件中的广播按钮
        button.setOnClickListener(new View.OnClickListener() {  //为按钮设置单击事件
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //定义广播的事件类型
                intent.setAction("mahuateng");
                sendBroadcast(intent);//发送广播

                //2.静态注册广播代码；
          /*      Intent intent=new Intent(); //创建Intent对象
                intent.setComponent( new ComponentName( "cn.hngy.broadcastdemo" ,
                        "cn.hngy.broadcastdemo.MyReceiver") );
                intent.setAction("zuckerberg"); //为Intent添加动作
                sendBroadcast(intent); //发送广播*/


            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}